package moe.kotake.webbehw.controller;


import com.fasterxml.jackson.annotation.JsonView;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import moe.kotake.webbehw.entity.content;
import moe.kotake.webbehw.entity.user;
import moe.kotake.webbehw.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import moe.kotake.webbehw.common.SMSResult;

import javax.annotation.Resource;
import javax.swing.text.AbstractDocument;
import javax.validation.Valid;
import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;

@RestController
@Tag(name = "SMSRestApi v1", description = "使用自定义消息格式的SMS控制器")
@RequestMapping("/api/v3/sms")
public class basicSMSinRestApi {
//    final userRepo userRepo;
//    final contentRepo contentRepo;
    @Resource
    private userMapper UserMapper;
    @Resource
    private contentMapper ContentMapper;
    //login
    @Operation(summary = "处理登录信息", description = "若信息错误，则返回401")
    @GetMapping(path = "/login")
    public SMSResult<?> getLogin() {
        return SMSResult.ok();
    }
    @Operation(summary = "处理登录信息", description = "若信息错误，则返回401")
    @PostMapping(path = "/login",consumes = "application/json")
    public SMSResult<?> login(@Valid @RequestBody user thisuser, BindingResult result) {
        if(result.hasErrors())
        {
            return SMSResult.error(401,"wrong password or email format!");
        }
//        if(userRepo.existsByEmailAndPassword(thisuser.getEmail(), thisuser.getPassword())) {

        if(UserMapper.selectAllByEmailAndPassword(thisuser.getEmail(), thisuser.getPassword()).isPresent()) {
            return SMSResult.ok("logged in!");
        }
        else {
            return SMSResult.error(401,"wrong password or email!");
        }
    }
    //signup
    @Operation(summary = "注册新用户", description = "若已经注册，则返回403;若格式不符返回401")
    @PostMapping(path = "/signup",consumes = "application/json")
    public SMSResult<?> signup(@Valid @RequestBody user thisuser, BindingResult result) {
        if(result.hasErrors())
        {
            return SMSResult.error(401,"wrong password or email format!");
        }
        if(UserMapper.selectAllByEmail(thisuser.getEmail()).isPresent()){
            return SMSResult.error(403,"user exist!");
        }
        else {
//            userRepo.save(thisuser);
            UserMapper.insert(thisuser);
            return SMSResult.ok("signed up!");
        }
    }
    //getUser
    @Operation(summary = "获取个人信息", description = "若无该用户，则返回404")
    @GetMapping(path = "/user/{id}",produces = "application/json")
    @JsonView(user.userSimpleView.class)
    public SMSResult<?> getUser(@PathVariable("id") Long id) {
//        Optional<user> u = userRepo.findById(id);
        assert UserMapper != null;
        user u = UserMapper.selectById(id);
        if(u!=null){
            System.out.println(u.getName());
            System.out.println(u.getEmail());
            return SMSResult.ok(u);
        }
        else{
            return SMSResult.error(404,"no such user!");
        }
    }
    //change user
    @Operation(summary = "更改个人信息", description = "若无该用户，则返回404;若格式不符返回401")
    @PutMapping(path = "/user/{id}",consumes = "application/json")
    @JsonView(user.userDataView.class)
    public SMSResult<?> changeUser(@PathVariable("id") Long id,@Valid @RequestBody user thisuser, BindingResult result){
        if(result.hasErrors())
        {
            return SMSResult.error(401,"wrong password or email format!");
        }
        if(UserMapper.selectById(id)!=null)
        {
            if(!UserMapper.selectAllByEmail(thisuser.getEmail()).get().getId().equals(id))
            {
                return SMSResult.error(403,"email already exist!");
            }
            else
            {
                user temp = new user(id,thisuser.getName(),thisuser.getPassword(),thisuser.getEmail());
                temp.setFriends(thisuser.getFriends());
                UserMapper.insert(temp);
//                userRepo.save(temp);
                return SMSResult.ok("changes saved!");
            }
        }
        else
        {
            return SMSResult.error(404,"no user!");
        }
    }
    //getList
    @Operation(summary = "获取个人信息流", description = "")
    @GetMapping(path = "/{id}", produces = "application/json")
    public SMSResult<?> getList(@PathVariable("id") Long id) {
//        user me = userRepo.findById(id).get();
        user me = UserMapper.selectById(id);
        String friendList = me.getFriends();
        String[] friends = friendList.split("&");
        System.out.println(friendList);
        List<content> contents = null;
        for (String friend : friends) {
            List<content> temp = ContentMapper.selectAllByPoster(Long.valueOf(friend));
            System.out.println(friend);
            if (!temp.isEmpty()) {
                System.out.println(temp.size());
                if (contents == null) {
                    System.out.println("empty->notempty!");
                    contents = temp;
                } else {
                    contents.addAll(temp);
                }
            }
        }
        for(content c : contents){
            System.out.println(c.getContent());
        }
        if(contents==null)
        {
            return SMSResult.error("no content!");
        }
        return SMSResult.ok(contents);
    }
    //postMsg
    @Operation(summary = "发送动态", description = "")
    @PostMapping(path = "/{id}",consumes = "application/json",produces = "application/json")
    public SMSResult<?> postContent(@PathVariable("id") Long id,@RequestBody String con){
        content temp = new content();
        temp.setTime(new Timestamp(System.currentTimeMillis()));
        temp.setContent(con);
        temp.setPoster(id);
        ContentMapper.insert(temp);
//        contentRepo.save(temp);
        return SMSResult.ok("content created!");
    }
    //deleteMsg
    @Operation(summary = "删除动态信息", description = "若信息错误，则返回401")
    @DeleteMapping(path = "/{id}",consumes = "application/json")
    public SMSResult<?> deleteContent(@PathVariable("id") Long id,@RequestBody Long cid)
    {
        if(ContentMapper.selectById(cid)!=null && ContentMapper.selectByIdAndPoster(cid,id)!=null)
        {
            ContentMapper.deleteById(cid);
            return SMSResult.ok("deleted!");
        }
        else
        {
            return SMSResult.error(404,"no such content");
        }
    }
}
